package com.example.testproj.serializable;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.testproj.R;
import com.example.testproj.utils.ThreadUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class SerializableTestActivity extends AppCompatActivity {
    private static final String TAG = "SerializableTestActivit";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serializable_test);

        ThreadUtil.getThreadUtil().submit(new Runnable() {
            @Override
            public void run() {
                try{
                    SerializableTest1 serializableTest1 = new SerializableTest1("测试类");
                    Log.d(TAG, "run: serializableTest1==="+ serializableTest1);

                    writeObject(serializableTest1);

                    Object serializableTest2 =  readObject();
                    Log.d(TAG, "run: serializableTest2==="+ serializableTest2);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        });
    }

    private Object readObject() {
        InputStream inputStream=null;
        try {
            File file = Environment.getExternalStorageDirectory();
            File saveFile = new File(file.getAbsolutePath() + "/test.obj");
            inputStream = new FileInputStream(saveFile);
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
           return  objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    private void writeObject(SerializableTest1 serializableTest1) {
        OutputStream outputStream=null;
        try {
            File file = Environment.getExternalStorageDirectory();
            File saveFile = new File(file.getAbsolutePath() + "/test.obj");
            outputStream = new FileOutputStream(saveFile);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(serializableTest1);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
